package cn.itcast.zt.java8.disruptor;

import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

import java.util.concurrent.Executors;

/**
 * 整合Spring，对Disruptor进行初始化
 * 这里注释掉整合部分 自行解决 整合时可以还原
 * @author zhangtian105
 * @date 2023/4/25
 * @apiNote
 */
/*@Service*/
public class NotifyServiceImpl implements INotifyService/*, DisposableBean, InitializingBean*/ {
    private Disruptor<NotifyEvent> disruptor ;
    private static final int RING_BUFFER_SIZE = 1024*1024 ;

    @Override
    public void sendNotify(String message) {
        // 非与spring整合处理
        disruptor = new Disruptor<>(new NotifyEventFactory(), RING_BUFFER_SIZE,
                Executors.defaultThreadFactory(), ProducerType.SINGLE, new BlockingWaitStrategy()) ;
        disruptor.setDefaultExceptionHandler(new NotifyEventHandlerException());
        disruptor.handleEventsWith(new NotifyEventHandler()) ;
        disruptor.start();

        RingBuffer<NotifyEvent> ringBuffer = disruptor.getRingBuffer() ;
        //        ringBuffer.publishEvent(new EventTranslatorOneArg<NotifyEvent,  String>() {
        //            @Override
        //            public void translateTo(NotifyEvent event, long sequence, String data) {
        //                event.setMessage(data);
        //            }
        //        }, message);
        //lambda式写法，如果是用jdk1.8以下版本使用以上注释的一段
        ringBuffer.publishEvent((event, sequence, data) -> event.setMessage(data), message);

        // 非与spring整合处理
        disruptor.shutdown();
    }

    /*@Override
    public void destroy() throws Exception {
        disruptor.shutdown();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        disruptor = new Disruptor<>(new NotifyEventFactory(), RING_BUFFER_SIZE,
                Executors.defaultThreadFactory(), ProducerType.SINGLE, new BlockingWaitStrategy()) ;
        disruptor.setDefaultExceptionHandler(new NotifyEventHandlerException());
        disruptor.handleEventsWith(new NotifyEventHandler()) ;
        disruptor.start();
    }*/
}
